package com.zhangjingcheng.yunyixia.service.impl;

import com.zhangjingcheng.yunyixia.constant.MessageConstant;
import com.zhangjingcheng.yunyixia.exception.UserBusinessException;
import com.zhangjingcheng.yunyixia.service.EmailService;
import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class EmailServiceImpl implements EmailService {

    @Autowired
    private JavaMailSender javaMailSender;

    @Override
    public void sendHtml(String from, String to, String subject, String content) {
        MimeMessage message = javaMailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            // 设置邮件内容为 HTML 格式
            helper.setText(content, true);
            javaMailSender.send(message);
            log.info("HTML 邮件发送成功，收件人: {}", to);
        } catch (MessagingException e) {
            log.error("HTML 邮件发送失败，收件人: {}", to, e);
            throw new UserBusinessException(MessageConstant.EMAIL_ERROR);
        }
    }
}